package com.mvc.web.common.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;

public class OSSManageUtil {
	
	private static int M = 5;
	 
    /**   
    * @Description: Oss上传
    * @author 白海安 （baihaian@126.com） 2016年6月29日 上午11:02:27
    * @version V1.0   
    */
    public static String uploadFile(InputStream fileContent,String file_name) throws Exception{  
    	OSSClient ossClient=new OSSClient(OSSConfigure.getEndpoint(), OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());  
    	
    	//创建上传Object的Metadata  
    	ObjectMetadata objectMetadata=new ObjectMetadata();  
    	objectMetadata.setContentLength(fileContent.available());  
    	objectMetadata.setCacheControl("no-cache");  
    	objectMetadata.setHeader("Pragma", "no-cache");  
    	objectMetadata.setContentType(contentType(file_name.substring(file_name.lastIndexOf(".")+1)));  
    	//attachment，inline
//    	objectMetadata.setContentType("application/vnd.android.package-archive");
    	objectMetadata.setContentDisposition("inline;filename=" + file_name);  
    	//上传文件  
    	ossClient.putObject(OSSConfigure.getBucketName(),file_name, fileContent, objectMetadata);  
    	objectMetadata=null;
    	ossClient=null;
    	fileContent=null;
    	return OSSConfigure.getAccessUrl() + file_name;  
    }
    
    public static String uploadFileAndDownload(InputStream fileContent,String bucketName,String file_name) throws Exception{  
    	OSSClient ossClient=new OSSClient(OSSConfigure.getEndpoint(), OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());  
    	
    	//创建上传Object的Metadata  
    	ObjectMetadata objectMetadata=new ObjectMetadata();  
    	objectMetadata.setContentLength(fileContent.available());  
    	objectMetadata.setCacheControl("no-cache");  
    	objectMetadata.setHeader("Pragma", "no-cache");  
    	objectMetadata.setContentType(contentType(file_name.substring(file_name.lastIndexOf(".")+1)));  
    	objectMetadata.setContentDisposition("attachment;filename=" + file_name);  
    	//上传文件  
    	ossClient.putObject(bucketName,   file_name, fileContent, objectMetadata);  
    	fileContent=null;
    	objectMetadata=null;
    	ossClient=null;
    	fileContent=null;
    	return OSSConfigure.getAccessUrl() + file_name;  
    }
    
    
    /**   
    * @Description: 分片上传
    * @author 白海安 （baihaian@126.com） 2016年8月31日 下午3:08:18
    * @version V1.0   
    */
    public static void uploadPartFile(File partFile,String bucketName,String key) throws Exception{
    	System.out.println("t1=="+System.currentTimeMillis());
    	OSSClient client=new OSSClient(OSSConfigure.getEndpoint(), OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());
    	// 开始Multipart Uploado
    	InitiateMultipartUploadRequest initiateMultipartUploadRequest =  new InitiateMultipartUploadRequest(bucketName, key);
    	InitiateMultipartUploadResult initiateMultipartUploadResult = client.initiateMultipartUpload(initiateMultipartUploadRequest);
    	// 打印UploadId
    	System.out.println("UploadId: " + initiateMultipartUploadResult.getUploadId());
    	// 设置每块为 5M
    	final  int partSize = 1024 * 1024 * M;
    	// 计算分块数目
    	int partCount = (int) (partFile.length() / partSize);
    	if (partFile.length() % partSize != 0){
    		partCount++;
    	}
    	// 新建一个List保存每个分块上传后的ETag和PartNumber
    	List<PartETag> partETags =  new ArrayList<PartETag>();
    	for( int i = 0; i < partCount; i++){
	    	// 获取文件流
	    	FileInputStream fis =  new FileInputStream(partFile);
	    	// 跳到每个分块的开头
	    	long skipBytes = partSize * i;
	    	fis.skip(skipBytes);
	    	// 计算每个分块的大小
	    	long size = partSize < partFile.length() - skipBytes ?
	    	partSize : partFile.length() - skipBytes;
	    	// 创建UploadPartRequest，上传分块
	    	UploadPartRequest uploadPartRequest =  new UploadPartRequest();
	    	uploadPartRequest.setBucketName(bucketName);
	    	uploadPartRequest.setKey(key);
	    	uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
	    	uploadPartRequest.setInputStream(fis);
	    	uploadPartRequest.setPartSize(size);
	    	uploadPartRequest.setPartNumber(i + 1);
	    	UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
	    	// 将返回的PartETag保存到List中。
	    	partETags.add(uploadPartResult.getPartETag());
    	}
    	
    	CompleteMultipartUploadRequest completeMultipartUploadRequest =
    			new CompleteMultipartUploadRequest(bucketName,key, initiateMultipartUploadResult.getUploadId(), partETags);
    			// 完成分块上传
    	CompleteMultipartUploadResult completeMultipartUploadResult =
    			client.completeMultipartUpload(completeMultipartUploadRequest);
    	// 打印Object的ETag
    	System.out.println(completeMultipartUploadResult.getETag());
    	System.out.println("t2=="+System.currentTimeMillis());
    }
    
    
    /**   
    * @Description: 设置文件属性
    * @author 白海安 （baihaian@126.com） 2016年6月29日 上午10:55:00
    * @version V1.0   
    */
    public static String CopyObject(String key,String value,String bucketName){  
    	OSSClient ossClient=new OSSClient(OSSConfigure.getEndpoint(), OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());  
    	//创建上传Object的Metadata  
    	ObjectMetadata objectMetadata=new ObjectMetadata();  
    	objectMetadata.setCacheControl("no-cache");  
    	objectMetadata.setHeader("Pragma", "no-cache");  
    	objectMetadata.setContentType(contentType(value.substring(value.lastIndexOf(".")+1)));  
    	objectMetadata.setContentDisposition("inline;filename=" + value);  
    	//上传文件  
    	CopyObjectRequest copy = new CopyObjectRequest(bucketName, key, bucketName, key);
    	copy.setNewObjectMetadata(objectMetadata);
    	CopyObjectResult res = ossClient.copyObject(copy);
    	System.out.println(res.toString());  
        objectMetadata=null;
        ossClient=null;
    	return res.toString();  
    }  
  
    /**   
    * @Description: 删除
    * @author 白海安 （baihaian@126.com） 2016年6月29日 上午10:56:37
    * @version V1.0   
    */
    public static void deleteLoanFile(String filename,String bucketName){  
    	OSSClient ossClient = new OSSClient(OSSConfigure.getEndpoint(),OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());  
    	ossClient.deleteObject(bucketName, filename);  
    }  
      
    /**   
    * @Description: 删除本地
    * @author 白海安 （baihaian@126.com） 2016年7月7日 下午2:08:32
    * @version V1.0   
    */
    public static void deleteDeskfile(String filepath) {
		java.io.File f = new java.io.File(filepath);
		// 检查File.txt是否存在
		if (f.exists()){
			f.delete();
		}
	}
    
    
     /** 
     * Description: 判断OSS服务文件上传时文件的contentType 
     * @Version1.0 
     * @param FilenameExtension 文件后缀 
     * @return String  
     */  
     public static String contentType(String FilenameExtension){  
        if(FilenameExtension.equals("BMP")||FilenameExtension.equals("bmp")){return "image/bmp";}  
        if(FilenameExtension.equals("GIF")||FilenameExtension.equals("gif")){return "image/gif";}  
        if(FilenameExtension.equals("JPEG")||FilenameExtension.equals("jpeg")||  
           FilenameExtension.equals("JPG")||FilenameExtension.equals("jpg")||     
           FilenameExtension.equals("PNG")||FilenameExtension.equals("png")){return "image/jpeg";}  
        if(FilenameExtension.equals("HTML")||FilenameExtension.equals("html")){return "text/html";}  
        if(FilenameExtension.equals("TXT")||FilenameExtension.equals("txt")){return "text/plain";}  
        if(FilenameExtension.equals("VSD")||FilenameExtension.equals("vsd")){return "application/vnd.visio";}  
        if(FilenameExtension.equals("PPTX")||FilenameExtension.equals("pptx")||  
            FilenameExtension.equals("PPT")||FilenameExtension.equals("ppt")){return "application/vnd.ms-powerpoint";}  
        if(FilenameExtension.equals("DOCX")||FilenameExtension.equals("docx")||  
            FilenameExtension.equals("DOC")||FilenameExtension.equals("doc")){return "application/msword";}  
        if(FilenameExtension.equals("XML")||FilenameExtension.equals("xml")){return "text/xml";}  
        return "text/html";  
     }  
     
     /**   
    * @Description: 根据图片key，下载到指定地址
    * @author 白海安 （baihaian@126.com） 2016年6月29日 上午10:57:07
    * @version V1.0   
    */
    public static String downloadFile(String key,String downpath,String bucketName){
     	OSSClient ossClient=new OSSClient(OSSConfigure.getEndpoint(), OSSConfigure.getAccessKeyId(), OSSConfigure.getAccessKeySecret());  
     	GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
 		ObjectMetadata objectMetadata = ossClient.getObject(getObjectRequest, new File(downpath));
 		return objectMetadata.getETag();
     }
     
    
    public static String getKey(String originalFilename) {
    	String  key = ToolsUtils.letter2Num(UUID.randomUUID().toString().replace("-", ""));
        //获取图片后缀
		int index = originalFilename.lastIndexOf(".");
		if(index == -1){
			return "";
		}
		String imgExt = "jpg|jpeg|png|bmp|gif";
		String suffix = originalFilename.substring(index+1);
		//校验文件格式
		if (imgExt.indexOf(suffix.toLowerCase()) < 0) {
			return "";
		}
		return key+"."+suffix;
    }
    
    
     public static void main(String[] args) throws Exception {
//    	 String path = "D:"+File.separator+"测试.jpg";
	    /*URL url = new URL("");
        URLConnection uc = url.openConnection();
        String fileName = uc.getHeaderField(6);
        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
        System.out.println("文件名为："+fileName);
        System.out.println("文件大小："+(uc.getContentLength()/1024)+"KB");
        FileOutputStream os = new FileOutputStream(path);
        InputStream is = uc.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
        os.close();
        is.close();
        System.out.println("下载成功,文件保存在："+path);*/
    	 
    	/*downloadFile("4955062361175733205.jpg", path, OSSConfigure.getBucketNameLoanFile()); */
    	 
//    	 deleteLoanFile("upw_20160523.rar", OSSConfigure.getBucketNameLoanFile());
    	 for (int i = 46; i < 48; i++) {
			System.out.println(i);
		}
    	 
    	 
	}
}
